use rocket::{form::Form, post, serde::{json::Json, Serialize}, FromForm, State};
use serde::Deserialize;
use uuid::Uuid;

use crate::Context;

use super::Resp;

#[derive(Clone,Debug,Serialize,Deserialize,FromForm)]
pub struct User {
    pub id:Option<String>,
    pub username:Option<String>,
    pub password:Option<String>,
}
rbatis::crud!(User {},"tb_users");
rbatis::impl_select!(
    User{select_by_id(table_name:&str,id:&str) -> Option => "`where id = #{id}`"}
);


#[post("/user",data="<user>")]
pub async fn add_user(ctx: &State<Context>,user:Option<Form<User>>) -> &'static str{
    let _ = match user {
        Some(u) =>User::insert(&ctx.database.db, &u).await.expect("insert failed"),
        None => return ""
    };
    return "success"
}


#[post("/users",data="<user>")]
pub async fn add_users(ctx: &State<Context>,mut user:Json<User>) -> Json<Resp<String>>{
    user.id=Some(String::from(Uuid::new_v4()));
    user.password=Some(String::from(format!("{:x}",md5::compute(user.clone().password.clone().unwrap()))));
    let _ = User::insert(&ctx.database.db, &user).await.expect("insert failed");
    let mut resp:Resp<String> = Resp::new(100, "".to_string(), vec![]);
    resp.set_statust(200);
    resp.set_msg("success".to_string());
    resp.set_data(vec![]);
    return Json(resp)

}

#[post("/login",data="<u>")]
pub async fn login(ctx: &State<Context>,u:Json<User>) -> Json<Resp<()>>{
    let us = User::select_by_column(&ctx.database.db, "username", u.username.clone().expect("faild")).await;
    let us = match  us {
        Ok(uu) => uu[0].clone(),
        Err(_er) => User { id: None, username: None, password: None },
    };
    
    let pw = md5::compute(u.password.clone().expect("faild"));
    //println!("{:x}",pw);
    //println!("{}",us.get(0).unwrap().password.clone().unwrap());
    //let a = us.get(0).unwrap().password.clone().unwrap().ne( &format!("{:x}",pw));
    // 
    if  us.password.clone().unwrap().eq(&format!("{:x}",pw))  {
        return Json(Resp::new(200, "success".to_string(), vec![]));
    }else {
        return Json(Resp::new(400, "faild".to_string(), vec![]));
    }
}
